package com.bdqn.config.shiro;

import com.bdqn.pojo.Right;
import com.bdqn.pojo.Role;
import com.bdqn.pojo.User;
import com.bdqn.service.UserService;
import jakarta.annotation.Resource;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.Set;


public class MyShiroRealm extends AuthorizingRealm {
    @Resource
    private UserService userService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("调用MyShiroRealm.doGetAuthenticationInfo获取身份信息！");
        UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken;
        String usrName=token.getUsername();
        User user=userService.getUserByUsrName(usrName);
        if (user==null){
            throw new UnknownAccountException();
        }
        if (user.getUsrFlag()==null||user.getUsrFlag().intValue()==0){
            throw new LockedAccountException();
        }
        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(user,user.getUsrPassword(),getName());
        return info;
    }



    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("调用MyShiroRealm.doGetAuthorizationInfo获取权限信息！");
        User user=(User) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
//        info.addRole(user.getRole().getRoleName());
//        info.addStringPermission("用户列表");       // 所有用户拥有“用户列表”权限
//        if ("管理员".equals(user.getRole().getRoleName())){
//            info.addStringPermission("用户添加");
//            info.addStringPermission("用户编辑");
//            info.addStringPermission("用户删除");
//        }
        Role role=user.getRole();
        if (role!=null){
            info.addRole(user.getRole().getRoleName());
            Set<Right> rights=role.getRights();
            if (rights!=null&&rights.size()>0){
                for (Right right:rights){
                    info.addStringPermission(right.getRightCode());
                }
            }
        }
        return info;
    }
}
